package tournament.volleyball;

import java.util.ArrayList;

public class Division {
	private static int nextId = 0;
	private int id;
	
	private String divisionName;
	
	public ArrayList<Rivalry> rivalries;
	public ArrayList<Team> teams;
	
	public Division() {
	}
	
	// Constructors: take various forms of scheduling and team names
	Division(String[] teamNames, int[] playOrder){
		this.teams = createTeams(teamNames);
		Schedule schedule = new Schedule();
		this.rivalries = schedule.setupSchedule(playOrder, teams);
		
		this.id = nextId;
		Division.nextId++;
	}
	
	Division(ArrayList<Team> teams, int[] playOrder){
		this.teams = teams;
		Schedule schedule = new Schedule();
		this.rivalries = schedule.setupSchedule(playOrder, teams);
		
		this.id = nextId;
		Division.nextId++;
	}
	
	Division(String[] teamNames, ArrayList<Game> games, int divId) {
		this.id = divId;
	}
	
	
	// Simple method to take an array of strings and return a list of teams with those respective names
	public ArrayList<Team> createTeams(String[] teamNames){
		ArrayList<Team> teams = new ArrayList<Team>();
		
		for (int i=0; i<teamNames.length; i++){
			teams.add(new Team(teamNames[i]));
		}
		
		return teams;
	}
	
	public void setName(String name) {
		this.divisionName = name;
	}
	
	public String getName() {
		return divisionName;
	}
	
	public Team getHigherPlacing(Team team1, Team team2) {
		if ((team1.getWins() > team2.getWins()) || 
				((team1.getWins() == team2.getWins()) && (team1.getSpread() > team2.getSpread()))) {
			return team1;
		} else if ((team2.getWins() > team1.getWins()) || 
				((team2.getWins() == team1.getWins()) && (team2.getSpread() > team1.getSpread()))) {
			return team2;
		} else {
			return null;
		}
	}
	
	public Team getDivisionWinner() {
		Team divisionLeader = teams.get(0);
		for (int i=0; i<teams.size(); i++) {
			if (teams.get(i).getWins() > divisionLeader.getWins()) {
				divisionLeader = teams.get(i);
			}
		}
		return divisionLeader;
	}
	
	public void sortTeams() {
		Team highest = teams.get(0);
		ArrayList<Team> sorted = new ArrayList<Team>();
		
		while (0<teams.size()) {
			highest = teams.get(0);
			for (int j=1; j<teams.size(); j++) {
				highest = getHigherPlacing(teams.get(j), highest);
				if (highest == null) {
					highest = teams.get(j); // Necessary in case there is a tie
				}
			}
			sorted.add(highest);
			teams.remove(highest);
		}
		teams.clear();
		
		teams.addAll(sorted);
	}
	
	public Rivalry getRivalry(int i) {
		return this.rivalries.get(i);
	}
	
	public Team getTeam(int i) {
		return this.teams.get(i);
	}
	
	public int getId() {
		return id;
	}
}
